package com.zjw.nanyinge.utils;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.BeanUtils;

import java.io.ByteArrayInputStream;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.*;

public class DomUtils {

    public static <T> T getObject(String chat, Class<T> clazz) {
        T t;
        SAXReader reader = new SAXReader();
        try {
            Document document = reader.read(new ByteArrayInputStream(chat.getBytes(StandardCharsets.UTF_8)));
            Element root = document.getRootElement();
            List<Element> elements = root.elements();
            t = BeanUtils.instantiateClass(clazz);
            Field[] declaredFields = clazz.getDeclaredFields();
            Map<String, Field> fieldMap = new HashMap<>();
            for (Field field : declaredFields) {
                field.setAccessible(true);
                fieldMap.put(field.getName().toLowerCase(Locale.ROOT), field);
            }
            for (Element element : elements) {
                Field field = fieldMap.get(element.getName().toLowerCase(Locale.ROOT).replace("_", ""));
                if (Objects.isNull(field)) {
                    continue;
                }
                field.set(t, element.getStringValue());
            }
        } catch (DocumentException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        return t;
    }
}
